"""
快速开始示例 - 智能路由系统

展示如何快速使用路由系统。

作者: RedFire Team
创建日期: 2025-10-06
"""

import asyncio
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

logger = logging.getLogger(__name__)


async def example_1_basic_routing():
    """
    示例1：基本路由使用
    
    演示如何初始化路由系统并执行简单的路由。
    """
    print("\n" + "="*60)
    print("示例1：基本路由使用")
    print("="*60)
    
    from app.adapters.manager import AdapterManager
    from app.utils.router_integration import initialize_routing_system
    from app.routing.strategy import create_routing_context
    from config.service_config import get_config
    
    # 1. 获取配置
    config = get_config()
    logger.info("✓ 配置加载完成")
    
    # 2. 初始化适配器管理器
    adapter_manager = AdapterManager(config=config)
    await adapter_manager.initialize()
    logger.info(f"✓ 适配器管理器初始化完成，共 {len(adapter_manager.get_all_adapters())} 个适配器")
    
    # 3. 初始化路由系统
    routing_components = await initialize_routing_system(
        adapter_manager=adapter_manager,
        config=config,
        start_monitoring=True
    )
    router = routing_components['router']
    logger.info("✓ 路由系统初始化完成")
    
    # 4. 创建路由上下文
    context = create_routing_context(
        request_type="get_realtime_quote",
        symbols=["000001.SZ"]
    )
    
    # 5. 执行路由
    result = await router.route(context)
    
    # 6. 查看结果
    if result.is_valid():
        print(f"\n✓ 路由成功！")
        print(f"  主适配器: {result.primary_adapter}")
        print(f"  备选适配器: {result.fallback_adapters}")
        print(f"  置信度: {result.confidence_score:.2f}")
        print(f"  路由原因: {result.routing_reason}")
    else:
        print(f"\n✗ 路由失败: {result.routing_reason}")
    
    # 7. 清理
    from app.utils.router_integration import shutdown_routing_system
    await shutdown_routing_system(routing_components)
    logger.info("✓ 路由系统已关闭")


async def example_2_orchestrator_usage():
    """
    示例2：使用编排器获取数据
    
    演示如何使用编排器自动路由和执行请求。
    """
    print("\n" + "="*60)
    print("示例2：使用编排器获取数据")
    print("="*60)
    
    from app.adapters.manager import AdapterManager
    from app.utils.router_integration import initialize_routing_system
    from app.orchestration.orchestrator import OrchestrationStrategy
    from config.service_config import get_config
    
    # 初始化
    config = get_config()
    adapter_manager = AdapterManager(config=config)
    await adapter_manager.initialize()
    
    routing_components = await initialize_routing_system(
        adapter_manager=adapter_manager,
        start_monitoring=True
    )
    orchestrator = routing_components['orchestrator']
    
    # 测试不同的编排策略
    strategies = [
        (OrchestrationStrategy.SEQUENTIAL, "串行获取（自动故障转移）"),
        (OrchestrationStrategy.PARALLEL, "并行获取"),
        (OrchestrationStrategy.FASTEST, "竞速模式"),
    ]
    
    for strategy, desc in strategies:
        print(f"\n{desc}:")
        try:
            result = await orchestrator.get_data(
                request_type="get_realtime_quote",
                strategy=strategy,
                symbols=["000001.SZ"]
            )
            print(f"  ✓ 成功获取数据: {type(result).__name__}")
        except Exception as e:
            print(f"  ✗ 失败: {e}")
    
    # 清理
    from app.utils.router_integration import shutdown_routing_system
    await shutdown_routing_system(routing_components)


async def example_3_health_monitoring():
    """
    示例3：健康监控
    
    演示如何查看适配器健康状态。
    """
    print("\n" + "="*60)
    print("示例3：健康监控")
    print("="*60)
    
    from app.adapters.manager import AdapterManager
    from app.utils.router_integration import initialize_routing_system
    from config.service_config import get_config
    
    # 初始化
    config = get_config()
    adapter_manager = AdapterManager(config=config)
    await adapter_manager.initialize()
    
    routing_components = await initialize_routing_system(
        adapter_manager=adapter_manager,
        start_monitoring=True
    )
    health_monitor = routing_components['health_monitor']
    
    # 等待一次健康检查
    await asyncio.sleep(2)
    
    # 获取健康报告
    report = health_monitor.get_health_report()
    
    print(f"\n健康状态总览:")
    print(f"  总适配器数: {report['summary']['total_adapters']}")
    print(f"  健康: {report['summary']['healthy']}")
    print(f"  降级: {report['summary']['degraded']}")
    print(f"  不健康: {report['summary']['unhealthy']}")
    print(f"  整体状态: {report['summary']['overall_status']}")
    
    print(f"\n各适配器详细状态:")
    for name, status in report['adapters'].items():
        print(f"  {name}: {status['status']} ({status['response_time_ms']:.2f}ms)")
        if status['error_message']:
            print(f"    错误: {status['error_message']}")
    
    # 清理
    from app.utils.router_integration import shutdown_routing_system
    await shutdown_routing_system(routing_components)


async def example_4_custom_routing():
    """
    示例4：自定义路由偏好
    
    演示如何指定偏好数据源和排除某些数据源。
    """
    print("\n" + "="*60)
    print("示例4：自定义路由偏好")
    print("="*60)
    
    from app.adapters.manager import AdapterManager
    from app.utils.router_integration import initialize_routing_system
    from app.routing.strategy import create_routing_context
    from config.service_config import get_config
    
    # 初始化
    config = get_config()
    adapter_manager = AdapterManager(config=config)
    await adapter_manager.initialize()
    
    routing_components = await initialize_routing_system(
        adapter_manager=adapter_manager,
        start_monitoring=True
    )
    router = routing_components['router']
    
    # 测试不同的偏好设置
    test_cases = [
        {
            "name": "默认路由",
            "preferred": None,
            "excluded": None
        },
        {
            "name": "优先使用AKShare",
            "preferred": ["akshare"],
            "excluded": None
        },
        {
            "name": "排除InfluxDB",
            "preferred": None,
            "excluded": ["influxdb"]
        },
        {
            "name": "优先Tushare，排除CTP",
            "preferred": ["tushare"],
            "excluded": ["ctp"]
        }
    ]
    
    for test in test_cases:
        print(f"\n{test['name']}:")
        
        context = create_routing_context(
            request_type="get_realtime_quote",
            symbols=["000001.SZ"],
            preferred_providers=test['preferred'],
            excluded_providers=test['excluded']
        )
        
        result = await router.route(context)
        
        if result.is_valid():
            print(f"  ✓ 选中: {result.primary_adapter}")
            print(f"    原因: {result.routing_reason}")
        else:
            print(f"  ✗ 路由失败: {result.routing_reason}")
    
    # 清理
    from app.utils.router_integration import shutdown_routing_system
    await shutdown_routing_system(routing_components)


async def example_5_routing_stats():
    """
    示例5：查看路由统计
    
    演示如何查看路由性能统计。
    """
    print("\n" + "="*60)
    print("示例5：查看路由统计")
    print("="*60)
    
    from app.adapters.manager import AdapterManager
    from app.utils.router_integration import initialize_routing_system
    from app.routing.strategy import create_routing_context
    from config.service_config import get_config
    
    # 初始化
    config = get_config()
    adapter_manager = AdapterManager(config=config)
    await adapter_manager.initialize()
    
    routing_components = await initialize_routing_system(
        adapter_manager=adapter_manager,
        start_monitoring=True
    )
    router = routing_components['router']
    
    # 执行多次路由
    print("\n执行10次路由测试...")
    for i in range(10):
        context = create_routing_context(
            request_type="get_realtime_quote",
            symbols=[f"00000{i}.SZ"]
        )
        await router.route(context)
    
    # 获取统计信息
    stats = router.get_routing_stats()
    
    print(f"\n路由统计:")
    print(f"  运行时间: {stats['uptime_seconds']:.2f}秒")
    print(f"  总路由次数: {stats['total_routes']}")
    print(f"  总失败次数: {stats['total_failures']}")
    print(f"  策略数量: {stats['strategy_count']}")
    print(f"  启用策略数: {stats['enabled_strategy_count']}")
    
    print(f"\n各适配器统计:")
    for adapter, adapter_stats in stats['adapter_stats'].items():
        print(f"  {adapter}:")
        print(f"    路由次数: {adapter_stats['routes']}")
        print(f"    失败次数: {adapter_stats['failures']}")
        print(f"    成功率: {adapter_stats['success_rate']:.2%}")
    
    # 清理
    from app.utils.router_integration import shutdown_routing_system
    await shutdown_routing_system(routing_components)


async def example_6_circuit_breaker():
    """
    示例6：熔断器使用
    
    演示熔断器的基本使用。
    """
    print("\n" + "="*60)
    print("示例6：熔断器使用")
    print("="*60)
    
    from app.resilience.circuit_breaker import CircuitBreaker, CircuitBreakerConfig, CircuitBreakerOpenError
    
    # 创建熔断器
    config = CircuitBreakerConfig(
        failure_threshold=3,  # 3次失败后熔断
        timeout=2.0,          # 2秒后尝试恢复
        success_threshold=2   # 2次成功后关闭熔断
    )
    
    cb = CircuitBreaker("test_service", config)
    
    # 模拟函数
    call_count = 0
    
    async def unstable_func():
        nonlocal call_count
        call_count += 1
        
        # 前5次调用失败
        if call_count <= 5:
            raise ValueError(f"模拟失败 (第{call_count}次)")
        
        # 之后成功
        return f"成功 (第{call_count}次)"
    
    # 测试熔断器
    for i in range(10):
        try:
            result = await cb.call(unstable_func)
            print(f"  第{i+1}次调用: ✓ {result}")
        except ValueError as e:
            print(f"  第{i+1}次调用: ✗ {e}")
        except CircuitBreakerOpenError:
            print(f"  第{i+1}次调用: ⚡ 熔断器打开，拒绝调用")
        
        print(f"    熔断器状态: {cb.state.value}")
        
        # 等待一会
        if i == 4:
            print("\n  等待熔断器超时...")
            await asyncio.sleep(2.1)
    
    # 查看统计
    stats = cb.get_stats()
    print(f"\n熔断器统计:")
    print(f"  总调用: {stats['total_calls']}")
    print(f"  成功: {stats['successful_calls']}")
    print(f"  失败: {stats['failed_calls']}")
    print(f"  拒绝: {stats['rejected_calls']}")
    print(f"  状态变更: {stats['state_transitions']}")


async def example_7_rate_limiter():
    """
    示例7：限流器使用
    
    演示限流器的基本使用。
    """
    print("\n" + "="*60)
    print("示例7：限流器使用")
    print("="*60)
    
    from app.resilience.rate_limiter import TokenBucketRateLimiter
    
    # 创建限流器：每秒5个请求
    limiter = TokenBucketRateLimiter(
        name="api_limiter",
        rate=5.0,
        capacity=10
    )
    
    print(f"限流器配置: 每秒5个请求，桶容量10")
    
    # 快速发送15个请求
    print(f"\n快速发送15个请求:")
    allowed = 0
    rejected = 0
    
    for i in range(15):
        if await limiter.acquire():
            allowed += 1
            print(f"  请求{i+1}: ✓ 允许")
        else:
            rejected += 1
            print(f"  请求{i+1}: ✗ 被限流")
    
    print(f"\n结果: 允许{allowed}个，拒绝{rejected}个")
    
    # 查看统计
    stats = limiter.get_stats()
    print(f"\n限流器统计:")
    print(f"  总请求: {stats['total_requests']}")
    print(f"  允许: {stats['allowed_requests']}")
    print(f"  拒绝: {stats['rejected_requests']}")
    print(f"  拒绝率: {stats['rejection_rate']:.2%}")
    print(f"  可用令牌: {stats['available_tokens']}")


async def main():
    """运行所有示例"""
    examples = [
        ("基本路由", example_1_basic_routing),
        ("编排器使用", example_2_orchestrator_usage),
        ("健康监控", example_3_health_monitoring),
        ("自定义路由", example_4_custom_routing),
        ("路由统计", example_5_routing_stats),
        ("熔断器", example_6_circuit_breaker),
        ("限流器", example_7_rate_limiter),
    ]
    
    print("\n" + "="*60)
    print("RedFire 智能路由系统 - 快速开始示例")
    print("="*60)
    print("\n选择要运行的示例:")
    for i, (name, _) in enumerate(examples, 1):
        print(f"  {i}. {name}")
    print(f"  0. 运行所有示例")
    
    try:
        choice = input("\n请输入选项 (0-7): ").strip()
        choice = int(choice) if choice else 0
        
        if choice == 0:
            # 运行所有示例
            for name, func in examples:
                try:
                    await func()
                except Exception as e:
                    logger.error(f"示例 '{name}' 运行失败: {e}", exc_info=True)
        elif 1 <= choice <= len(examples):
            # 运行指定示例
            name, func = examples[choice - 1]
            await func()
        else:
            print("无效的选项")
    
    except ValueError:
        print("无效的输入")
    except KeyboardInterrupt:
        print("\n\n用户中断")
    except Exception as e:
        logger.error(f"运行失败: {e}", exc_info=True)
    
    print("\n" + "="*60)
    print("示例运行完成！")
    print("="*60)


if __name__ == "__main__":
    asyncio.run(main())

